package com.marvels.financial.pay.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.marvels.common.dto.MarvelsApiResultDTO;
import com.marvels.common.dto.pay.MarvelsPayResultDTO;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.exception.MarvelsErrorCode;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;
import com.marvels.financial.loan.dto.RepaymentNoMobileDTO;
import com.marvels.financial.pay.bfpay.dto.BfPaymentCallBackDTO;
import com.marvels.financial.pay.bfpay.dto.BfPaymentNotifyDTO;
import com.marvels.financial.pay.bfpay.service.BfPayApi;
import com.marvels.financial.pay.dto.McfeMerchantRechargeRecordDTO;
import com.marvels.financial.pay.dto.MerchantRechargeCallBackDTO;
import com.marvels.financial.pay.dto.MerchantRechargeDTO;
import com.marvels.financial.pay.hjpay.dto.DirectPaymentDTO;
import com.marvels.financial.pay.hjpay.dto.DirectPaymentQueryDTO;
import com.marvels.financial.pay.hjpay.dto.DirectPaymentSmsDTO;
import com.marvels.financial.pay.hjpay.dto.LoanPaymentCallBackDTO;
import com.marvels.financial.pay.hjpay.dto.PaymentCallBackDTO;
import com.marvels.financial.pay.hjpay.service.HjPayApi;
import com.marvels.financial.pay.service.PayService;

import net.sf.json.JSONObject;


/**
 * 
* @ClassName: PayController 
* @Description: 支付+绑卡 
* @author 李瑶
* @date 2018年10月19日 上午9:39:23 
*
 */
@RequestMapping("financial/pay/api")
@RestController
public class PayController {
	
	@Autowired
	private BfPayApi bfPayApi;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
	
	@Autowired
	private PayService payService;
	
	@Autowired
	private HjPayApi hjPayApi;
	
	@Value("${config.properties.path}")
	private  String configPropertiesPath;
	/**
	 * 
	* @Title: queryBindedList 
	* @Description:已绑卡列表  
	* @param idno 身份证号码
	* @return       
	* @author 李瑶
	* @date 2018年10月19日 上午9:41:51
	 */
	@RequestMapping("queryBindedList")
	@ResponseBody
	public MarvelsPayResultDTO queryBindedList(@RequestBody Map<String, Object> param){
		try {
			String idno = (String)param.get("idno");
			String paymentChannel  = ServerProperties.getValue(configPropertiesPath, "common.properties", "payment_channel");
			return payService.queryBindedSuccessList(idno, paymentChannel);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>查询卡列表异常", e);
			return MarvelsPayResultDTO.getResult("-1", "查询绑卡列表异常", null);
		}
	}
	
	
	/**
	 * 查询绑卡列表  当前通道未绑卡则返回之前通道的绑卡信息 
	 * @param param
	 * @return
	 */
	@RequestMapping("bankBindList")
	@ResponseBody
	public MarvelsPayResultDTO bankBindList(@RequestBody Map<String, Object> param){
		try {
			return payService.bankBindList(param);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>查询绑卡列表异常", e);
			return MarvelsPayResultDTO.getResult("-1", "查询绑卡列表异常", null);
		}
	}
	
	
	
	/**
	 * 
	* @Title: queryBind 
	* @Description:查询用户是否已经绑定卡 
	* @param idno 身份证号码
	* @return       
	* @author 李瑶
	* @date 2018年10月19日 上午9:41:51
	 */
	@RequestMapping("queryBind")
	@ResponseBody
	public MarvelsPayResultDTO queryBind(@RequestBody Map<String, Object> param){
		try {
			String idno = (String)param.get("idno");
			String bindCardNo = (String)param.get("bindCardNo");
			String paymentChannel  = ServerProperties.getValue(configPropertiesPath, "common.properties", "payment_channel");
			return payService.queryBind(idno, bindCardNo,paymentChannel);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>查询绑卡异常", e);
			return MarvelsPayResultDTO.getResult("-1", "查询绑卡异常", null);
		}
	}
	
	
	/**
	 * 
	* @Title: preBindCard 
	* @Description:预绑卡  
	* @param bankCardNo
	* @param idno
	* @param userName
	* @param phone
	* @return       
	* @author 李瑶
	* @date 2018年10月19日 上午9:45:40
	 */
	@RequestMapping("preBindCard")
	@ResponseBody
	public MarvelsPayResultDTO preBindCard(@RequestBody Map<String, Object> param){
		try {
			String paymentChannel  = ServerProperties.getValue(configPropertiesPath, "common.properties", "payment_channel"); 
			return payService.preBind(param, paymentChannel);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>预绑卡异常", e);
			return MarvelsPayResultDTO.getResult("-1", "查询绑卡列表异常", null);
		}
	}
	
	/**
	 * 
	* @Title: bindCard 
	* @Description:绑卡  
	* @param requestNo 预绑卡返回的请求号
	* @param validateCode 验证码
	* @return       
	* @author 李瑶
	* @date 2018年10月19日 上午10:45:46
	 */
	@RequestMapping("bindCard")
	@ResponseBody
	public MarvelsPayResultDTO bindCard(@RequestBody Map<String, Object> param){
		try {
			String requestNo = (String)param.get("requestNo");
			String validateCode = (String)param.get("validateCode");
			String mobileNo = (String)param.get("mobileNo");
			String paymentChannel  = ServerProperties.getValue(configPropertiesPath, "common.properties", "payment_channel");
			return payService.bindCard(requestNo, validateCode, paymentChannel,mobileNo);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>预绑卡异常", e);
			return MarvelsPayResultDTO.getResult("-1", "查询绑卡列表异常", null);
		}
	}
	
	/**
	 * 
	* @Title: bindCard 
	* @Description:绑卡  
	* @param requestNo 预绑卡返回的请求号
	* @param validateCode 验证码
	* @return       
	* @author 李瑶
	* @date 2018年10月19日 上午10:45:46
	 */
	@RequestMapping("queryBindCardInfoById")
	@ResponseBody
	public MarvelsPayResultDTO queryBindCardInfoById(@RequestBody Map<String, Object> param){
		try {
			String bindId = null == param.get("bindId")?"":param.get("bindId").toString();
			if(StringUtils.isEmpty(bindId)){
				return MarvelsPayResultDTO.getResult("-1", "绑定卡信息入参为空", null);
			}
			return payService.queryBindCardInfoById(Long.parseLong(bindId));
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>查询绑卡详情异常", e);
			return MarvelsPayResultDTO.getResult("-1", "查询绑卡详情异常", null);
		}
	}
	
	
	/**
	 * 
	* @Title: queryBnakCardBinFromMerchant 
	* @Description:从支付公司查询卡bin信息  
	* @param param
	* @return       
	* @author 李瑶
	* @date 2018年11月2日 下午5:38:15
	 */
	@RequestMapping("queryBnakCardBinFromMerchant")
	@ResponseBody
	public MarvelsPayResultDTO queryBnakCardBinFromMerchant(@RequestBody Map<String, Object> param){
		try {
			String bankCardNo = null == param.get("bankCardNo")?"":param.get("bankCardNo").toString();
			if(StringUtils.isEmpty(bankCardNo)){
				return MarvelsPayResultDTO.getResult("-1", "绑定卡信息入参为空", null);
			}
			String paymentChannel  = ServerProperties.getValue(configPropertiesPath, "common.properties", "payment_channel");
			return payService.getBankCardInfo(bankCardNo,paymentChannel);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>从支付公司查询卡bin信息异常", e);
			return MarvelsPayResultDTO.getResult("-1", "从支付公司查询卡bin信息异常", null);
		}
	}
	
	
	
	/**
	 * 汇聚协议代扣异步通知
	 * @param param
	 * @return
	 */
	@RequestMapping("hjPaymentNotify")
	@ResponseBody
	public String ybPaymentNotify(PaymentCallBackDTO callBackDTO){
		MarvelsLogUtil.getInstance().info(">>>>>汇聚协议代扣异步通知参数:"+JSONObject.fromObject(callBackDTO));
		try {
			 hjPayApi.ybPaymentNotify(callBackDTO);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error(">>>>>汇聚协议代扣异步通知处理失败", e);
			return "fail";
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>汇聚协议代扣异步通知处理异常", e);
			return "fail";
		}
		return "SUCCESS";
	}
	
	
	@RequestMapping("merchantRecharge")
	@ResponseBody
	public MarvelsPayResultDTO merchantRecharge(@RequestBody MerchantRechargeDTO merchantRechargeDTO){
		try {
			return payService.merchantRecharge(merchantRechargeDTO);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error(">>>>>>>>>商户充值失败", e);
			return MarvelsPayResultDTO.getResult("-1", "商户充值失败", null);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>商户充值异常", e);
			return MarvelsPayResultDTO.getResult("-1", "商户充值异常", null);
		}
	}
	
	
	
	/**
	 * 汇聚商户充值回调
	 * @param merchantRechargeCallBackDTO
	 * @return
	 */
	@RequestMapping("hjMerchantRechargeCallBack")
	@ResponseBody
	public String hjMerchantRechargeCallBack(MerchantRechargeCallBackDTO merchantRechargeCallBackDTO){
		try {
			MarvelsLogUtil.getInstance().info(">>>>>>>>>汇聚商户充值回调"+JSON.toJSONString(merchantRechargeCallBackDTO));
			 hjPayApi.hjMerchantRechargeCallBack(merchantRechargeCallBackDTO);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error(">>>>>>>>>商户充值回调失败", e);
			return "fail";
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>商户充值回调异常", e);
			return "fail";
		}
		return "success";
				
	}
	
	
	/**
	 * 汇聚充值页面回调
	 * @param merchantRechargeCallBackDTO
	 * @return
	 */
	@RequestMapping("hjMerchantRechargeDeal")
	@ResponseBody
	public MarvelsPayResultDTO hjMerchantRechargeDeal(@RequestBody MerchantRechargeCallBackDTO merchantRechargeCallBackDTO){
		try {
			MarvelsLogUtil.getInstance().info(">>>>>>>>>汇聚充值页面回调"+JSON.toJSONString(merchantRechargeCallBackDTO));
			Map<String, Object> map=hjPayApi.hjMerchantRechargeCallBack(merchantRechargeCallBackDTO);
			return MarvelsPayResultDTO.getSuccessResult(map);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error(">>>>>>>>>商户充值处理失败", e);
			return MarvelsPayResultDTO.getResult("-1", "商户充值处理失败", null);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>商户充值处理失败", e);
			return MarvelsPayResultDTO.getResult("-1", "商户充值处理失败", null);
		}
				
	}
	
	/**
	 * 汇聚商户充值回调
	 * @param merchantRechargeCallBackDTO
	 * @return
	 */
	@RequestMapping("hjMerchantRechargeResult")
	@ResponseBody
	public MarvelsPayResultDTO hjMerchantRechargeResult(@RequestBody MerchantRechargeCallBackDTO merchantRechargeCallBackDTO){
		try {
			Map<String, Object> map=hjPayApi.hjMerchantRechargeCallBack(merchantRechargeCallBackDTO);
			return MarvelsPayResultDTO.getSuccessResult(map);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error(">>>>>>>>>商户充值失败", e);
			return MarvelsPayResultDTO.getResult("-1", "商户充值失败", null);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>商户充值异常", e);
			return MarvelsPayResultDTO.getResult("-1", "商户充值异常", null);
		}
				
	}
	
	
	/**
	 * 查询商户余额
	 * @param merchantRechargeDTO
	 * @return
	 */
	@RequestMapping("merchantBalance")
	@ResponseBody
	public MarvelsPayResultDTO merchantBalance(@RequestBody MerchantRechargeDTO merchantRechargeDTO){
		try {
			return payService.merchantBalance(merchantRechargeDTO);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error(">>>>>>>>>查询商户余额失败", e);
			return MarvelsPayResultDTO.getResult("-1", "查询商户余额失败", null);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>查询商户余额异常", e);
			return MarvelsPayResultDTO.getResult("-1", "查询商户余额异常", null);
		}
	}
	
	
	/**
	 * 查询商户充值记录
	 * @param mcfeMerchantRechargeRecordDTO
	 * @return
	 */
	@RequestMapping("merchantRechargeRecord")
	@ResponseBody
	public MarvelsPayResultDTO merchantRechargeRecord(@RequestBody McfeMerchantRechargeRecordDTO mcfeMerchantRechargeRecordDTO){
		try {
			Page<McfeMerchantRechargeRecordDTO> list=payService.merchantRechargeRecord(mcfeMerchantRechargeRecordDTO);
			return MarvelsPayResultDTO.getSuccessResult(list);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error(">>>>>>>>>查询商户充值记录失败", e);
			return MarvelsPayResultDTO.getResult("-1", "查询商户充值记录失败", null);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>查询商户充值记录异常", e);
			return MarvelsPayResultDTO.getResult("-1", "查询商户充值记录异常", null);
		}
				
	}
	
	
	@RequestMapping("paymentTest")
	@ResponseBody
	public String paymentTest(@RequestBody Map<String, Object> map){
		String orderNo=String.valueOf(map.get("q1OrderNo"));
		if("1".equals(String.valueOf(map.get("type")))){
			DirectPaymentSmsDTO smsDTO=new DirectPaymentSmsDTO();
			smsDTO.setQ1_OrderNo(orderNo);
			smsDTO.setQ2_Amount(new BigDecimal(String.valueOf(map.get("q2Amount"))).setScale(2,BigDecimal.ROUND_HALF_UP));
			smsDTO.setS1_PayerName(String.valueOf(map.get("s1PayerName")));
			smsDTO.setS3_PayerCardNo(String.valueOf(map.get("s3PayerCardNo")));
			smsDTO.setS4_PayerBankCardNo(String.valueOf(map.get("s4PayerBankCardNo")));
			smsDTO.setS7_BankMobile(String.valueOf(map.get("s7BankMobile")));
			Map<String, Object> dataMap=new HashMap<String, Object>();
			try {
				dataMap=hjPayApi.directPaymentSms(smsDTO);
			} catch (MarvelsBusinessException e) {
				MarvelsLogUtil.getInstance().error(">>>>>快捷 支付短信接口请求异常:",e);
			}
			MarvelsLogUtil.getInstance().info(">>>>>快捷 支付短信接口返回结果:"+JSONObject.fromObject(dataMap));
		}
		
		if("2".equals(String.valueOf(map.get("type")))){
			DirectPaymentDTO directPaymentDTO=new DirectPaymentDTO();
			directPaymentDTO.setQ1_OrderNo(orderNo);
			directPaymentDTO.setS1_PayerName(String.valueOf(map.get("s1PayerName")));
			directPaymentDTO.setS3_PayerCardNo(String.valueOf(map.get("s3PayerCardNo")));
			directPaymentDTO.setS4_PayerBankCardNo(String.valueOf(map.get("s4PayerBankCardNo")));
			directPaymentDTO.setS7_BankMobile(String.valueOf(map.get("s7BankMobile")));
			directPaymentDTO.setQ2_Amount(new BigDecimal(String.valueOf(map.get("q2Amount"))).setScale(2,BigDecimal.ROUND_HALF_UP));
			directPaymentDTO.setQ4_ProductName(String.valueOf(map.get("q4ProductName")));
			directPaymentDTO.setT2_SmsCode(String.valueOf(map.get("t2SmsCode")));
			Map<String, Object> dataMap2=new HashMap<String, Object>();
			try {
				dataMap2=hjPayApi.directPayment(directPaymentDTO);
			} catch (MarvelsBusinessException e) {
				MarvelsLogUtil.getInstance().error(">>>>>快捷直接支付短信接口请求:",e);
			}
			MarvelsLogUtil.getInstance().info(">>>>>快捷直接支付短信接口返回结果:"+JSONObject.fromObject(dataMap2));
		}
		
		
		if("3".equals(String.valueOf(map.get("type")))){
			DirectPaymentQueryDTO queryDTO=new DirectPaymentQueryDTO();
			queryDTO.setP2_OrderNo(orderNo);
			Map<String, Object> dataMap3=new HashMap<String, Object>();
			try {
				dataMap3=hjPayApi.directPaymentQuery(queryDTO);
			} catch (MarvelsBusinessException e) {
				MarvelsLogUtil.getInstance().error(">>>>>快捷直接支付短信查询接口请求:",e);
			}
			MarvelsLogUtil.getInstance().info(">>>>>快捷直接支付短信查询接口返回结果:"+JSONObject.fromObject(dataMap3));
		}
		return orderNo;
	}
	
	/**
	 * 直接支付短信调用
	 * @param mcfeMerchantRechargeRecordDTO
	 * @return
	 */
	@RequestMapping("directPaymentSms")
	@ResponseBody
	public MarvelsApiResultDTO directPaymentSms(@RequestBody RepaymentNoMobileDTO repaymentNoMobileDTO){
		try {
			Map<String, Object> map=payService.directPaymentSms(repaymentNoMobileDTO);
			return MarvelsApiResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), "调用成功", map, null, null);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error(">>>>>>>>>直接支付短信调用失败", e);
			return   MarvelsApiResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(),e.getMessage(),null,null,null);// MarvelsApiResultDTO.getResult(MarvelsErrorCode.FAIL.getValue(),e.getMessage(), null
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>直接支付短信调用异常", e);
			return  MarvelsApiResultDTO.getResult(MarvelsErrorCode.ERROR.getValue(), "提交还款异常", null,null,null);
		}
				
	}

	/**
	 * 汇聚代付结果异步回调
	 * @param callBackDTO
	 * @return
	 */
	@RequestMapping("hjPayCallback")
	@ResponseBody
	public String hjPaymentCallBack(@RequestBody LoanPaymentCallBackDTO callBackDTO){
		MarvelsLogUtil.getInstance().info(">>>>>汇聚代付结果异步回调参数:"+JSONObject.fromObject(callBackDTO));
		JSONObject jsonObject=new JSONObject();
		try {
			 hjPayApi.hjPaymentCallBack(callBackDTO);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error(">>>>>汇聚代付结果异步回调处理失败", e);
			jsonObject.put("statusCode", "2002");
			jsonObject.put("message", "成功");
			return jsonObject.toString();
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>汇聚代付结果异步回调处理异常", e);
			jsonObject.put("statusCode", "2002");
			jsonObject.put("message", "成功");
			return jsonObject.toString();
		}
		jsonObject.put("statusCode", "2001");
		jsonObject.put("message", "成功");
		return jsonObject.toString();
	}
	
	
	/**
	 * 宝付协议代扣异步回调
	 * @param callBackDTO
	 * @return
	 */
	@RequestMapping("bfPaymentNotify")
	@ResponseBody
	public String bfPaymentNotify(BfPaymentNotifyDTO paymentNotifyDTO){
		MarvelsLogUtil.getInstance().info(">>>>>宝付协议代扣异步通知参数:"+JSON.toJSONString(paymentNotifyDTO));
		try {
			bfPayApi.bfPaymentNotify(paymentNotifyDTO);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error(">>>>>宝付协议代扣异步通知处理失败", e);
			return "fail";
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>宝付协议代扣异步通知处理异常", e);
			return "fail";
		}
		return "OK";
	}
	
	
	/**
	 * 宝付代付回调
	 * @param paymentNotifyDTO
	 * @return
	 */
	@RequestMapping("bfPaymentCallBack")
	@ResponseBody
	public String bfPaymentCallBack(BfPaymentCallBackDTO bfPaymentCallBackDTO){
		MarvelsLogUtil.getInstance().info(">>>>>宝付代付异步通知参数:"+JSON.toJSONString(bfPaymentCallBackDTO));
		try {
			bfPayApi.bfPaymentCallBack(bfPaymentCallBackDTO);
		}catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error(">>>>>宝付代付异步通知处理失败", e);
			return "fail";
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>宝付代付异步通知处理异常", e);
			return "fail";
		}
		return "OK";
	}
	
	
	
	
	
	/**
	 * 小贷公司进件申请回调
	 * @param callBackDTO
	 * @return
	 */
	@RequestMapping("yProjectLoanCaseCallback")
	@ResponseBody
	public String yProjectLoanCaseCallback(@RequestBody Map<String, String> callBackDTO){
		MarvelsLogUtil.getInstance().info(">>>>>小贷公司进件申请异步回调参数:"+JSONObject.fromObject(callBackDTO));
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("returnCode", "0000");
		jsonObject.put("message", "成功");
		return jsonObject.toString();
	}
	
	
	
	
	/**
	 * 小贷公司放款结果回调
	 * @param callBackDTO
	 * @return
	 */
	@RequestMapping("yProjectPayResultCallback")
	@ResponseBody
	public String yProjectPayResultCallback(@RequestBody Map<String, Object> callBackDTO){
		MarvelsLogUtil.getInstance().info(">>>>>小贷公司放款结果异步回调参数:"+JSONObject.fromObject(callBackDTO));
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("returnCode", "0000");
		jsonObject.put("message", "成功");
		return jsonObject.toString();
	}
}
